import axios from 'axios';
import config from '@/config/config.base.js';
import router from '@/router/index';
import { Toast } from 'vant';
//创建拦截器
let instance = axios.create({
  headers: {
    'content-type': 'application/json',
  },
});
//拦截器默认基础地址
// instance.defaults.baseURL = config.baseURL;
instance.defaults.baseURL = config.devBaseURL;

// 请求拦截器
instance.interceptors.request.use(
  options => {
    //在发送请求之前， 添加token的请求头，这里可以对请求前做相关操作回调
    if (localStorage.getItem('token')) {
      options.headers['Authorization'] = localStorage.getItem('token');
    }
    return options;
  },
  error => {
    //单请求错误的时候做相关操作
    return Promise.reject(error);
  }
);

//响应拦截器
instance.interceptors.response.use(
  response => {
    console.log(response);
    if (response.status === 200) {
      return response;
    } else {
      return Promise.reject(response.data);
    }
  },
  error => {
    console.log(error.response);
    if (error && error.response && error.response.status === 401) {
      Toast('未登录或权限过期，请登录后重试！');
      router.push({ path: `/login` });
    }
    return Promise.reject(error);
  }
);

export default instance;
